package ru.vsu.cs.kis.elections.socketexchenge.commands;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class CommandName extends Command {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1089074002122373872L;
	
	private Command comm;

	public CommandName(OutputStream aOutStr, InputStream aInStr) {
		super(aOutStr, aInStr);
	}

	public CommandName(OutputStream aOutStr, InputStream aInStr, Command command) {
		super(aOutStr, aInStr);
		this.comm = command;
	}

	public Command getCommand() {
		return comm;
	}

	@Override
	public Integer executeOnServer() throws IOException {
		BufferedReader reader=new BufferedReader(new InputStreamReader(aInStr));
		String cbuf=reader.readLine();
        try {
			 comm = (Command)(Class.forName(cbuf)).newInstance();
			 comm.setInputStream(aInStr);
			 comm.setOutputStream(aOutStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (comm!=null){
			return(1);
		}
		return (-1);
	}

	@Override
	public Integer executeOnClient() throws IOException {		
		BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(aOutStr));
		writer.write(comm.getClass().getName()+"\n");
		writer.flush();
		return (1);
	}

}
